#include "db.h"



DB::DB(const char *host, const char *username, const char *password, const char *dbname)
{
    //初始化数据库句柄
    mysql=mysql_init(NULL);
    if(!mysql)
    {
        qDebug()<<"初始化数据库失败\n";
        exit(-1);
    }
    MYSQL*con=mysql_real_connect(mysql,host,username,password,dbname,0,NULL,0);
    if(con==NULL)
    {
        qDebug()<<"链接数据库失败\n";
        exit(-1);
    }
    int ret=mysql_query(mysql,"set names utf8");
    if(ret!=0)
    {
        qDebug()<<"设置字符集失败\n";
        exit(-1);
    }
    qDebug()<<"链接成功\n";
}

bool DB::db_exec(const char *sql)
{
    unique_lock<std::mutex>lock(mutex);
    int ret=mysql_query(mysql,sql);
    if(ret!=0)
    {
        qDebug()<<"mysql 语句失败\n"<<mysql_errno(mysql);
        return false;
    }
    cout<<" 插入成功（db_exec）\n";
    return true;
}

bool DB::db_select(const char *sql, json& j) {
    unique_lock<std::mutex> lock(mutex);

    // 执行查询
    if (mysql_query(mysql, sql) != 0) {
        qDebug() << "查询失败:" << mysql_error(mysql);
        return false;
    }

    // 获取结果集
    MYSQL_RES* sql_res = mysql_store_result(mysql);
    if (!sql_res) {
        if (mysql_errno(mysql) != 0) {
            qDebug() << "获取结果失败:" << mysql_error(mysql);
        }
        return (mysql_errno(mysql) == 0);
    }

    // 获取字段信息
    unsigned num_fields = mysql_num_fields(sql_res);
    MYSQL_FIELD* fields = mysql_fetch_fields(sql_res);

    json result_array;
    MYSQL_ROW row;

    // 处理每一行数据（
    while ((row = mysql_fetch_row(sql_res))) {
        json current_row;
        for (unsigned i = 0; i < num_fields; i++) {
            if (row[i] == nullptr) {
                current_row[fields[i].name] = nullptr;
            } else {
                current_row[fields[i].name] = row[i];
            }
        }
        result_array.push_back(current_row); // 每行只添加一次
    }

    j = result_array; // 修复：在循环外赋值
    mysql_free_result(sql_res);
    cout<<"查询成功\n";
    return true;
}
